package com.api.common.config;

import io.lettuce.core.RedisURI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 崔老爷
 * Date: 2024/10/26 11:26
 * @Description:
 */
//@Configuration
//@ConfigurationProperties(prefix = "spring")
//@Slf4j
public class RedisTemplateConfig {
    /**
     * redis端口
     */

    private String host;
    /**
     * redis端口
     */

    private int port;
    //    /**
//     * redis密码
//     */
//
//    private String passWord;
//    /**
//     * 最大连接数
//     */
//
//    private int maxIdl;
//    /**
//     * 最小空闲连接数
//     */
//
//    private int minIdl;
//    /**
//     * 超时时间
//     */
//
//    private int timeout;
//    /**
//     * 配置需要操作的db
//     */
//
    private List<Integer> dbs;
    /**
     * 默认的db
     */
    private int defaultDb;
    /**
     * 存储redisTemplate
     */
    private static Map<Integer, RedisTemplate<String, Object>> redisTemplateMap = new HashMap<>();

    /**
     * 初始化dbs各自的redisTemplate
     */
//    @PostConstruct
//    public void initRedisTemp() throws Exception {
//        log.info("###### START 初始化 Redis 连接池 START ######");
//        defaultDb = dbs.get(0);
//        for (Integer db : dbs) {
//            log.info("###### 正在加载Redis-db-" + db + " ######");
//            redisTemplateMap.put(db, redisTemplate(redisConnectionFactory(db)));
//        }
//        log.info("###### END 初始化 Redis 连接池 END ######");
//    }
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        //定义redis key的序列化
        redisTemplate.setKeySerializer(RedisSerializer.string());

        return redisTemplate;
    }

    // 自定义 Redis 连接工厂
    public RedisConnectionFactory redisConnectionFactory(int database) {
        LettuceConnectionFactory factory = new LettuceConnectionFactory();

        RedisConfiguration redisConfiguration = LettuceConnectionFactory.createRedisConfiguration(RedisURI.create(host, port));

        factory.setDatabase(database);
        return factory;
    }
}
